package cn.parllay.dingdangproject.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.HandlerThread;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import cn.parllay.dingdangproject.DingDangApplication;
import cn.parllay.dingdangproject.R;
import cn.parllay.dingdangproject.entity.LoginMsg;
import cn.parllay.dingdangproject.global.API;
import cn.parllay.dingdangproject.utils.ConnectionManager;
import cn.parllay.dingdangproject.utils.SocketChanelManager;
import cn.parllay.dingdangproject.utils.SpUtils;
import cn.parllay.dingdangproject.widget.MyWindowManager1;

/**
 * Created by sunny on 2018/1/18.
 */

public class MyNoticeService extends Service {

    private static final String TAG = "MyNoticeService";
    public static final int NOTICE_ID = 100;
    private final int mPort = 9999;
    private final String mHost = "47.104.82.9";
    private NoticeThread mNoticeThread;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.e(TAG, "启动VIP通知服务");

        //如果API大于18，需要弹出一个可见通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setContentTitle("KeepAppAlive");
            builder.setContentText("MyNoticeService is runing...");
            startForeground(NOTICE_ID, builder.build());
            // 如果觉得常驻通知栏体验不好
            // 可以通过启动CancelNoticeService，将通知移除，oom_adj值不变
            Intent intent = new Intent(this, CancelNoticeService.class);
            startService(intent);
        } else {
            startForeground(NOTICE_ID, new Notification());
        }

        MyWindowManager1.getInstance().init(getApplicationContext());
        mNoticeThread = new NoticeThread("notice");

        mNoticeThread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 如果Service被终止
        // 当资源允许情况下，重启service
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mNoticeThread = null;
        MyWindowManager1.getInstance().disMissWindow();
        // 如果Service被杀死，干掉通知
        if (Build.VERSION.SDK_INT
                >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            NotificationManager mManager =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mManager.cancel(NOTICE_ID);
        }
        Log.e(TAG, "DaemonService---->onDestroy，前台service被杀死");
        // 重启自己
        Intent intent = new Intent(getApplicationContext(), MyNoticeService.class);
        startService(intent);
    }

    class NoticeThread extends HandlerThread {

        private ConnectionManager connectionManager;
        private boolean isConnected;

        public NoticeThread(String name) {
            super(name);
            connectionManager = new ConnectionManager(mPort, API.getServiceHost());
        }

        @Override
        protected void onLooperPrepared() {

            Log.e(TAG, "22222222222222222222");
            long millis = System.currentTimeMillis();
            SpUtils.getInstance(getApplicationContext()).save(SpUtils.LOGIN_TIME, millis);
            String storeNo = SpUtils.getInstance(getApplicationContext()).getString(SpUtils.STORE_NO, "");

            Log.e(TAG,"登入"+storeNo + ": " + SpUtils.getInstance(DingDangApplication.getContext()).getLong(SpUtils.LOGIN_TIME,0));
            Log.e(TAG, "storeNo == " + storeNo);
            for (; ; ) {
                isConnected = connectionManager.connect();
                if (isConnected) {
                    Log.e(TAG, "连接成功");

                    LoginMsg loginMsg = new LoginMsg();
                    loginMsg.setUserName(storeNo + millis);
                    loginMsg.setPassword(storeNo + millis);
                    SocketChanelManager.getInstance().writeToServer(loginMsg);
                    break;
                }
                try {
                    sleep(3000);
                    Log.e(TAG, "尝试重新连接。。。");
                } catch (Exception e) {

                }
            }
        }

    }
}
